/**
 * Created by Administrator on 2017/2/17.
 */
function writeObj(obj){
    var description = "";
    for(var i in obj){
        var property=obj[i];
        description+=i+" = "+property+"\n";
    }
    alert(description);
}

/**
 * 判断对象是否为空
 */
function isEmptyObject(obj){
    for(var key in obj){
        break;  return false
    };
    return true
};

var map, geolocation, x, y, address,proviceid,cityid,districtid,name;
var is_Loc = false;
var store_list,distans;
$(function(){
    Init();
    function Init() {
        param = {};
        if(proviceid){
             param.province_id = proviceid;
        }
        if(cityid){
             param.city_id = cityid;
        }
        if(districtid){
             param.disid = districtid;
        }
        if(name){
             param.name = name;
        }
        $.ajax({
            url: ApiUrl + "/index.php?act=store&op=business_store",
            data:param,
            type: 'get',
            dataType: 'json',
            success: function (result) {
                if (result['code'] == 200) {
                    store_list = document.getElementById('list_con').getElementsByTagName('div');
                    distans = document.getElementsByClassName('distans');
                    result.datas.SITEURL = SITEURL;
                    var html = template.render('class', result.datas);
                    $('#class-box').html(html);
                    if(result.datas.business_store[0]) {
                        var storelist = template.render("store", result.datas);
                        $("#list_con").html(storelist);
                    }else{
                        $("#list_con").html('<p>暂无数据</p>');
                    }

                    var bannerlist = template.render("banner", result.datas);
                    $("#swipe").html(bannerlist);
                    var mySwipe = new Swipe(document.getElementById('slider'), {
                        startSlide: 0,  //起始图片切换的索引位置
                        auto: 3000, //设置自动切换时间，单位毫秒
                        continuous: true,  //无限循环的图片切换效果
                        disableScroll: false,  //阻止由于触摸而滚动屏幕
                        stopPropagation: true,  //停止滑动事件
                        callback: function (index, element) {
                        },  //回调函数，切换时触发
                        transitionEnd: function (index, element) {
                        }  //回调函数，切换结束调用该函数
                    });
                }
                if(param.city_id){
                     location();
                }
            }
        });
    }
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('container', {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
    var disArr = [];
    var calculated = 0;
    //解析定位结果
    function onComplete(data) {
        dis = data.addressComponent.district;
        $("#area_info").val(dis);
        name = dis;
        postion = data.position;
        address = data.formattedAddress;
        y = data.position.getLng();
        x = data.position.getLat();
        Init();
        is_Loc = true;
        location();
    }

    function location(){
        if(!is_Loc || store_list.length==0){
              return;
        }
        calculated = 0;
        disArr = [];
        for (var i = 0; i<store_list.length; i++){
            var store_id = store_list[i].getAttribute('data-id');
            var data = {x:x,y:y,store_id:store_id,i:i};
            $.ajax({
                type:"POST",
                url:ApiUrl+"/index.php?act=store&op=getStoreDistans",
                data:data,
                dataType:"json",
                success:function(data){
                    calculated++;
                    distansArr = {'k':data['datas']['_index'],'dis':data['datas']['distans']};
                    disArr.push(distansArr);
                    if(data['datas']['distans']==undefined){
                            distans[data['datas']['_index']].innerHTML = "";
                    }else{
                        if(data['datas']['distans']>1000) {
                            distans[data['datas']['_index']].innerHTML = fomatFloat(data['datas']['distans']/1000,1) + " km";
                        }else{
                            distans[data['datas']['_index']].innerHTML = data['datas']['distans'] + " m";
                        }
                    }

                }
            })
        }
        addListen();
    }

    // 监听计算距离事件
    function addListen(){
        var timer = null;
        timer = setInterval(function(){
              if(calculated>=store_list.length){
                  disArr.sort(by("dis"));
                  _reverhtml = '';
                  var list = document.getElementsByClassName('list');
                  for(key in disArr){
                       k = disArr[key]['k'];
                       _reverhtml+= "<div class='list'>"+list[k].innerHTML+"</div>";
                  }
                  $('#list_con').html(_reverhtml);
                  clearInterval(timer);
              }
         },1000)
    }
    //by函数接受一个成员名字符串做为参数
    //并返回一个可以用来对包含该成员的对象数组进行排序的比较函数
    var by = function(name){
        return function(o, p){
            var a, b;
            if (typeof o === "object" && typeof p === "object" && o && p) {
                a = o[name];
                b = p[name];
                if (a === b) {
                    return 0;
                }
                if (typeof a === typeof b) {
                    return a < b ? -1 : 1;
                }
                return typeof a < typeof b ? -1 : 1;
            }
            else {
                throw ("error");
            }
        }
    }
    //解析定位错误信息
    function onError(data) {
        //document.getElementById('tip').innerHTML = '定位失败';
    }
    function fomatFloat(src,pos){
        return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);
    }
    $("#area_info").on("click",
        function() {
            $.areaSelected({
                success: function(a) {
                    $("#area_info").val(a.area_name).attr({
                        "data-areaid": a.area_id,
                        "data-areaid2": a.area_id_2 == 0 ? a.area_id_1: a.area_id_2
                    })
                    proviceid = a.area_id_1;
                    cityid = a.area_id_2;
                    districtid = a.area_id_3;
                    name = '';
                    Init();
                }
            })
        });

    $page = 1;
    var isLock = false;
    $(window).scroll(function () {
        var windowheight=$(window).height();//窗口高度
        var scrolltop=$('body').scrollTop();//滚动条高度
        var eh=$(document).height();//文本高度
        if(parseInt(windowheight+scrolltop)+1>=eh&&isLock==false){
            isLock = true;
            document.getElementsByClassName('list_loading')[0].style.display = 'block';
            $page++;
            $.ajax({
                url:ApiUrl+"/index.php?act=store&op=business_store&page="+$page,
                type:'get',
                dataType:'json',
                success:function(result) {
                    if (result['code'] == 200) {

                        document.getElementsByClassName('list_loading')[0].style.display = 'none';
                        result.datas.SITEURL = SITEURL;
                        if (isEmptyObject(result.datas.business_store)) {
                            isLock = true;
                            document.getElementsByClassName('nodata')[0].style.display = 'block';
                        }else{
                            store_list = document.getElementById('list_con').getElementsByTagName('div');
                            distans = document.getElementsByClassName('distans');
                            var storelist = template.render("store", result.datas);
                            $("#list_con").html($("#list_con").html() + storelist);
                            location();
                        }
                    }
                }
            });
        }
    })

});

var toAddress = '';
// 选择导航软件
function nav(_this){
    toAddress =_this.getAttribute('data-address');
     $(".map_decation").css("bottom",0);
}

function closeNav(){
    $(".map_decation").css("bottom",-120);
}
/**
 * 到导航页
 */
function mapnavigation(op){
    if(op==1){
         window.location.href = WapSiteUrl+"/tmpl/map.html?start="+address+"&addressto="+toAddress;
    }else{
         window.location.href = WapSiteUrl+"/tmpl/baidumap.html?addressto="+toAddress;
    }
}

